<template>
    <div class="phase-begin-add-container">
        <!-- 顶部信息 -->
        <div class="top-form">
            <el-form :inline="true" :model="headerForm">
                <el-form-item label="期初日期">
                    <el-date-picker v-model="headerForm.PhaseBeginDate" type="date" placeholder="请选择日期" />
                </el-form-item>
                <el-form-item label="单据号">
                    <el-input v-model="headerForm.PhaseBeginNumber" placeholder="自动生成或输入" />
                </el-form-item>
                <el-form-item label="流水号">
                    <el-input v-model="headerForm.serialNumber" placeholder="自动生成或输入" />
                </el-form-item>
            </el-form>
        </div>

        <!-- 动态表格 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="earNumber" label="*耳号">
                <template #default="scope">
                    <el-select v-model="scope.row.SheepFilesId" placeholder="请选择耳号" filterable clearable
                        style="width: 120px;">
                        <el-option v-for="item in earNumberOptions" :key="item.Id" :label="item.Name"
                            :value="item.Id" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="houseName" label="*栋舍">
                <template #default="scope">
                    <el-select v-model="scope.row.BuildingId" placeholder="请选择栋舍" filterable clearable
                        style="width: 120px;">
                        <el-option v-for="item in houseOptions" :key="item.BuildingId" :label="item.House_name"
                            :value="item.BuildingId" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="fielName" label="栏位">
                <template #default="scope">
                    <el-select v-model="scope.row.Field" placeholder="请选择栏位" filterable clearable style="width: 120px;">
                        <el-option v-for="item in fieldOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="sheepCount" label="只数">
                <template #default="scope">
                    <el-input v-model="scope.row.SheepCount" :disabled="true" />
                </template>
            </el-table-column>
            <el-table-column prop="weight" label="重量(公斤)">
                <template #default="scope">
                    <el-input-number v-model="scope.row.Weight" :min="0" :precision="2" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="scope">
                    <el-button type="danger" size="small" @click="removeRow(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 合计与操作 -->
        <div class="table-footer" style="margin-top: 10px;">
            <el-button type="primary" @click="addRow">+ 增行</el-button>
            <el-button type="danger" @click="removeLastRow">- 删行</el-button>
            <span style="margin-left: 30px;">合计只数：{{ totalSheepCount }}</span>
            <span style="margin-left: 30px;">合计重量：{{ totalWeight }}</span>
        </div>

        <!-- 备注 -->
        <div style="margin-top: 20px;">
            <el-input v-model="remark" type="textarea" placeholder="请输入备注信息" />
        </div>

        <!-- 保存按钮 -->
        <div style="margin-top: 20px; text-align: right;">
            <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Sheep_BreedingWrite, Sheep_BreedingRead } from '@/utils/Interceptors'
import { useRouter } from 'vue-router'

const router = useRouter()

// 下拉数据
const earNumberOptions = ref([])
const houseOptions = ref([])
const fieldOptions = ref([])

// 获取耳号
const fetchEarNumbers = async () => {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    if (res.data && res.data.code === 200) {
        earNumberOptions.value = res.data.data || []
    }
}
// 获取栋舍
const fetchHouses = async () => {
    const res = await Sheep_BreedingRead.get('/api/SheepFiles/GetBuildingList')
    if (res.data && res.data.code === 200) {
        houseOptions.value = res.data.data || []
    }
}
// 获取栏位
const fetchFields = async () => {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName')
    if (res.data && res.data.code === 200) {
        fieldOptions.value = res.data.data || []
    }
}

// 自动生成单据号
const generateBillNumber = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const random = String(Math.floor(Math.random() * 9999)).padStart(4, '0')
    return `QC${year}${month}${day}${random}`
}

// 自动生成流水号
const generateSerialNumber = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')
    return `${year}${month}${day}${hour}${minute}${second}`
}

// 获取当前时间 ISO 格式
const getCurrentTime = () => {
    return new Date().toISOString()
}

onMounted(() => {
    // 自动生成单据号和流水号
    headerForm.PhaseBeginNumber = generateBillNumber()
    headerForm.serialNumber = generateSerialNumber()

    fetchEarNumbers()
    fetchHouses()
    fetchFields()
})

// 顶部表单
const headerForm = reactive({
    PhaseBeginDate: '',
    PhaseBeginNumber: '',
    serialNumber: ''
})

// 动态表格数据 - 确保初始值类型正确
const tableData = ref([
    {
        SheepFilesId: '',
        BuildingId: '',
        Field: '',
        SheepCount: 1,
        Weight: null
    }
])

// 合计
const totalSheepCount = computed(() => tableData.value.reduce((sum, row) => sum + (row.SheepCount || 0), 0))
const totalWeight = computed(() => tableData.value.reduce((sum, row) => sum + (Number(row.Weight) || 0), 0))

// 备注
const remark = ref('')

// 增加一行
const addRow = () => {
    tableData.value.push({
        SheepFilesId: '',
        BuildingId: '',
        Field: '',
        SheepCount: 1,
        Weight: null
    })
}

// 删除指定行
const removeRow = (index: number) => {
    if (tableData.value.length > 1) {
        tableData.value.splice(index, 1)
    } else {
        ElMessage.warning('至少保留一行')
    }
}

// 删除最后一行
const removeLastRow = () => {
    if (tableData.value.length > 1) {
        tableData.value.pop()
    } else {
        ElMessage.warning('至少保留一行')
    }
}

// 保存
const handleSave = async () => {
    // 增强校验
    if (!headerForm.PhaseBeginDate) {
        ElMessage.error('请选择期初日期')
        return
    }

    if (!headerForm.PhaseBeginNumber) {
        ElMessage.error('单据号不能为空')
        return
    }

    // 校验表格数据
    for (let i = 0; i < tableData.value.length; i++) {
        const row = tableData.value[i]
        if (!row.SheepFilesId || row.SheepFilesId === '' || row.SheepFilesId === 0) {
            ElMessage.error(`第${i + 1}行请选择耳号`)
            return
        }
        if (!row.BuildingId || row.BuildingId === '' || row.BuildingId === 0) {
            ElMessage.error(`第${i + 1}行请选择栋舍`)
            return
        }
        if (!row.SheepCount || row.SheepCount <= 0) {
            ElMessage.error(`第${i + 1}行羊只数量必须大于0`)
            return
        }

        // 验证数字字段是否为有效数字
        if (isNaN(Number(row.SheepFilesId))) {
            ElMessage.error(`第${i + 1}行耳号格式不正确`)
            return
        }
        if (isNaN(Number(row.BuildingId))) {
            ElMessage.error(`第${i + 1}行栋舍格式不正确`)
            return
        }
    }

    const currentTime = getCurrentTime()

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userName = userInfo.UserName || '系统用户'

    // 组装数据 - 确保所有数字字段都是有效的整数
    const payload = tableData.value.map(row => ({
        SheepFilesId: parseInt(row.SheepFilesId) || 0,
        BuildingId: parseInt(row.BuildingId) || 0,
        Field: row.Field ? parseInt(row.Field) : null, // 栏位也改为ID
        SheepCount: parseInt(row.SheepCount) || 1,
        Weight: row.Weight ? parseFloat(row.Weight) : 0,
        PhaseBeginDate: headerForm.PhaseBeginDate,
        PhaseBeginNumber: headerForm.PhaseBeginNumber,
        SerialNumber: headerForm.serialNumber,
        Remark: remark.value || '',
        Creator: userName,
        CreateTime: currentTime,
        Modifier: userName,
        ModifyTime: currentTime,
        Auditor: userName,
        AuditTime: currentTime,
        IsDeleted: false
    }))

    console.log('提交数据:', payload) // 调试用
    console.log('第一条数据的SheepFilesId类型:', typeof payload[0].SheepFilesId, payload[0].SheepFilesId)

    try {
        const res = await Sheep_BreedingWrite.post('/api/PhaseBegin/AddPhaseBegin', payload)
        console.log('API响应:', res.data) // 调试用

        if (res.data && res.data.code === 200) {
            ElMessage.success('保存成功')
            router.push({ name: 'PhaseBegin2' })
        } else {
            ElMessage.error(res.data?.msg || '保存失败')
            console.error('保存失败详情:', res.data)
        }
    } catch (e: any) {
        console.error('请求异常:', e)
        ElMessage.error(e?.response?.data?.msg || e?.message || '保存失败')
    }
}
</script>

<style scoped>
.phase-begin-add-container {
    padding: 20px;
    background: #fff;
    min-height: 100vh;
}

.top-form {
    margin-bottom: 20px;
}

.table-footer {
    display: flex;
    align-items: center;
    gap: 10px;
}
</style>
